<template>
  <div class="container">
    <el-main v-loading="loading" element-loading-text="loading..." style="min-height:120px;padding:0px;overflow:hidden">
      <el-row>
        <el-col>
          <el-radio-group v-model="searchDateType" style="margin:0 20px;" @change="getData">
            <el-radio :label="1">按日期查看</el-radio>
            <el-radio :label="0">按小时查看</el-radio>
          </el-radio-group>
          <date-range-picker
            v-show="searchDateType==1"
            v-model="searchdate"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            shortcuts="E"
            @change="getData" />
          <el-date-picker
            v-show="searchDateType==0"
            v-model="onedate"
            :picker-options="datePickerOptions"
            type="date"
            placeholder="选择日期"
            size="small"
            @change="getData"/>
        </el-col>
      </el-row>
      <el-row :gutter="30" style="margin-top:20px;">
        <el-col :sm="12" :xs="24">
          <div id="coin" :style="{width: '100%', height: '390px'}"/>
        </el-col>
        <el-col :sm="12" :xs="24">
          <div id="cash" :style="{width: '100%', height: '390px'}"/>
        </el-col>
      </el-row>
      <el-row :gutter="30" style="margin-top:20px;">
        <el-col :sm="12" :xs="24">
          <div id="cashExtract" :style="{width: '100%', height: '380px'}"/>
        </el-col>
        <el-col :sm="12" :xs="24">
          <div id="phoneBillExtract" :style="{width: '100%', height: '380px'}"/>
        </el-col>
      </el-row>
    </el-main>
  </div>
</template>
<script>
import { getCapitalFlowData } from '@/api/activity-anomaly-analysis.js';
import { dateShortcutKeyJS } from './../mixins/common.js';
import timeUtils from '@/utils/timeHandle.js';
import textFormatting from '@/utils/textFormatting.js';
import echarts from 'echarts';
export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      loading: false,
      searchdate: [
        timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        timeUtils.timeHandle(new Date().getTime(), 'date')
      ],
      onedate: timeUtils.timeHandle(new Date().getTime(), 'date'),
      searchDateType: 1,
      queryList: {
        dateType: 1,
        startTime: timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        endTime: timeUtils.timeHandle(new Date().getTime(), 'date')
      },
      barDataDic: {
        coin: 'totalCoinCount',
        cash: 'totalCashCount',
        cashExtract: 'totalWithdrawCashCount',
        phoneBillExtract: 'totalRechargeCashCount'
      },
      lineDataDic: {
        coin: 'averageCoinCount',
        cash: 'averageCashCount',
        cashExtract: 'averageWithdrawCashCount',
        phoneBillExtract: 'averageRechargeCashCount'
      },
      title: {
        coin: '金币产生实时分布情况',
        cash: '零钱产生实时分布情况',
        cashExtract: '申请提现零钱实时分布情况',
        phoneBillExtract: '申请零钱充值话费实时分布情况'
      },
      legend: {
        coin: ['金币总数', '人均金币'],
        cash: ['零钱总数', '人均零钱'],
        cashExtract: ['申请提现零钱总数', '人均申请提现零钱'],
        phoneBillExtract: ['零钱充值话费', '人均零钱充值话费']
      },
      axis: {
        coin: ['金币总数(千个)', '人均金币(个)'],
        cash: ['零钱总数(美元)', '人均零钱(美元)'],
        cashExtract: ['申请提现零钱总数(美元)', '人均申请提现零钱(美元)'],
        phoneBillExtract: ['零钱充值话费(美元)', '人均零钱充值话费(美元)']
      },
      canvas: {
        coin: null,
        cash: null,
        cashExtract: null,
        phoneBillExtract: null
      },
      timeBar: {
        coin: [],
        cash: [],
        cashExtract: [],
        phoneBillExtract: []
      },
      dateType: {
        coin: 1,
        cash: 1,
        cashExtract: 1,
        phoneBillExtract: 1
      },
      list: {
        coin: [],
        cash: [],
        cashExtract: [],
        phoneBillExtract: []
      },
      avgList: {
        coin: [],
        cash: [],
        cashExtract: [],
        phoneBillExtract: []
      },
      backHistroy: {
        coin: {},
        cash: {},
        cashExtract: {},
        phoneBillExtract: {}
      }
    };
  },
  mounted() {
    this.backHistroy = {
      coin: { ...this.queryList },
      cash: { ...this.queryList },
      cashExtract: { ...this.queryList },
      phoneBillExtract: { ...this.queryList }
    };
    window.addEventListener('resize', () => {
      Object.keys(this.canvas).forEach(item => {
        this.canvas[item].resize();
      });
    });
    this.getCanvasData('all');
  },
  methods: {
    getData() {
      this.queryList.dateType = this.searchDateType;
      const type = this.queryList.dateType;
      if (type === 0 && this.onedate == null) {
        this.$message.info('请选择日期，进行按小时查看');
        return false;
      } else if (type === 1 && this.searchdate == null) {
        this.$message.info('请选择日期，进行按日期查看');
        return false;
      }

      this.queryList = {
        dateType: type,
        startTime:
          type == 1
            ? timeUtils.timeHandle(this.searchdate[0], 'date')
            : timeUtils.timeHandle(this.onedate, 'date'),
        endTime:
          type == 1
            ? timeUtils.timeHandle(this.searchdate[1], 'date')
            : timeUtils.timeHandle(this.onedate, 'date')
      };

      this.dateType = {
        coin: type,
        cash: type,
        cashExtract: type,
        phoneBillExtract: type
      };

      this.getCanvasData('all');
    },
    initCanvas(canvasType) {
      const self = this;
      this.canvas[canvasType] = echarts.init(document.getElementById(canvasType));
      // 绘制图表配置coinCashProduceOp
      const option = {
        color: this.$store.state.app.eChartColor,
        title: {
          text: this.title[canvasType],
          subtext: `${
            self.dateType[canvasType] === 0 ? self.queryList.startTime : ''
          }`,
          x: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {
              title: '下载'
            },
            myBack: {
              // 自定义按钮
              show: self.dateType[canvasType] === 0, // 是否显示
              title: '返回',
              icon:
                'path://M315 232.6L293.8 213 11.6 516.5l21.2 19.6 264.8 284.7 21.2-19.6-251-269.9H897v-28.8H64.1L315 232.6z m641.5 270.5h56v27.1h-56v-27.1z', // 图标
              color: '#C0C4CC',
              onclick: function() {
                self.dateType[canvasType] = 1; // 按日期查询
                self.queryList = { ...self.backHistroy[canvasType] };
                self.getCanvasData(canvasType);
              }
            }
          }
        },
        grid: {
          show: false,
          top: '80',
          bottom: '60',
          right: '100',
          left: '100'
        },
        legend: [
          {
            show: true,
            selectedMode: 'multiple',
            top: 25,
            right: 10,
            data: self.legend[canvasType],
            textStyle: {
              color: '#666',
              fontSize: 12
            },
            itemGap: 20,
            x: 'left'
          }
        ],
        xAxis: [
          {
            type: 'category',
            triggerEvent: this.dateType[canvasType] === 1,
            data: this.timeBar[canvasType],
            axisPointer: {
              type: 'shadow'
            },
            axisTick: {
              show: true,
              interval: 0
            },
            axisLine: {
              lineStyle: {
                color: '#909399'
              }
            }
          }
        ],
        // 设置两个y轴，左边显示数量，右边显示概率
        yAxis: [
          {
            type: 'value',
            name: `${self.axis[canvasType][0]}`,
            axisLine: {
              lineStyle: {
                color: '#909399'
              }
            }
          },
          {
            type: 'value',
            name: `${self.axis[canvasType][1]}`,
            axisLine: {
              lineStyle: {
                color: '#909399'
              }
            }
          }
        ],
        // 每个设备分数量、概率2个指标，只要让他们的name一致，即可通过，legeng进行统一的切换
        series: [
          {
            name: `${self.axis[canvasType][0]}`,
            type: 'bar',
            data: this.list[canvasType],
            barWidth: '40%',
            itemStyle: {
              color: '#EC8433'
            }
          },
          {
            name: `${self.axis[canvasType][1]}`,
            type: 'line',
            yAxisIndex: 1, // 这里要设置哪个y轴，默认是最左边的是0，然后1，2顺序来。
            data: this.avgList[canvasType],
            symbolSize: 10,
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      };
      this.canvas[canvasType].setOption(option);
      //   设置点击x轴触发
      this.canvas[canvasType].off('click');
      this.canvas[canvasType].on('click', function(params) {
        if (self.dateType[canvasType] == 1) {
          if (
            params.componentType == 'xAxis' ||
            params.componentType == 'series'
          ) {
            // 将上一级数据存储
            self.backHistroy[canvasType] = {
              dateType: 1,
              startTime: timeUtils.timeHandle(self.searchdate[0], 'date'),
              endTime: timeUtils.timeHandle(self.searchdate[1], 'date')
            };
            self.dateType[canvasType] = 0; // 按时间查询
          }

          if (params.componentType == 'xAxis') {
            self.queryList = {
              dateType: 0,
              startTime: params.value,
              endTime: params.value
            };
          } else if (params.componentType == 'series') {
            self.queryList = {
              dateType: 0,
              startTime: params.name,
              endTime: params.name
            };
          }
          self.getCanvasData(canvasType);
        }
      });
    },
    // 获取页面数据
    getCanvasData(dataType) {
      this.loading = true;
      getCapitalFlowData(this.queryList)
        .then(result => {
          if (result.code == 200) {
            if (result.data.length === 0) {
              this.$message.info(
                `${this.queryList.startTime} ~ ${
                  this.queryList.endTime
                } 时间段暂无数据`
              );
              // 还原上级数据 请写代码
              this.queryList = { ...this.backHistroy[dataType] };
              this.dateType[dataType] = 1;
              return false;
            }
            const data = result.data;
            // 时间轴赋值
            if (this.queryList.dateType === 1) {
              Object.keys(this.timeBar).forEach(item => {
                this.timeBar[item] = data.map(item => item.date);
              });
            } else {
              Object.keys(this.timeBar).forEach(item => {
                this.timeBar[item] = data.map(item => item.date);
              });
            }
            // 图标数据赋值
            Object.keys(this.timeBar).forEach(item => {
              if (item == 'coin') {
                this.list[item] = data.map(
                  listItem => (listItem[this.barDataDic[item]] / 1000).toFixed(3)
                );
                this.avgList[item] = data.map(avgListItem =>
                  textFormatting.numToFixed(
                    avgListItem[this.lineDataDic[item]],
                    2
                  )
                );
              } else {
                this.list[item] = data.map(listItem =>
                  textFormatting.numToFixed(listItem[this.barDataDic[item]], 2)
                );
                this.avgList[item] = data.map(avgListItem =>
                  textFormatting.numToFixed(
                    avgListItem[this.lineDataDic[item]],
                    2
                  )
                );
              }
            });
            if (dataType === 'all') {
              // 更新所有图表
              Object.keys(this.timeBar).forEach(item => {
                this.initCanvas(item);
              });
            } else {
              // 更新指定图表
              this.initCanvas(dataType);
            }
            this.loading = false;
          } else {
            this.$message.error(result.msg);
            this.loading = false;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;
}

.chart {
  float: left;
  margin: 20px;
}
</style>
